/*
 * Copyright 2007-2009 Taglab Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.taglab.chic.taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * Wraps the tag's body with a javascript friendly XML CDATA section.
 *
 * <p>For example the following:
 * <code>
 *   <script>
 *
 *   </script>
 * </code>
 *
 * <p>translates to
 *
 * <code>
 *   &lt;script type="text/javascript"&gt;/*&lt;![CDATA[* /
 *   alert('hello world!);
 *   /*&lt;![CDATA[* /&lt;/script>
 * </code>
 *
 * @author Markus Kobler
 */
public class ScriptTag extends TagSupport {

  private final static String DEFUALT_SCRIPT_TYPE = "text/javascript"; 

  private String type = DEFUALT_SCRIPT_TYPE;
  
  @Override
  public int doStartTag() throws JspException {
    try {
      pageContext.getOut().write("<script type=\"");
      pageContext.getOut().write(type);
      pageContext.getOut().write("\">/*<![CDATA[*/");
      return EVAL_BODY_INCLUDE;
    } catch (IOException e) {
      throw new JspException(e.toString(), e);
    }
  }

  @Override
  public int doEndTag() throws JspException {
    try {
      pageContext.getOut().append("/*]]>*/</script>");    
      return EVAL_PAGE;
    } catch (IOException e) {
      throw new JspException(e.toString(), e);
    }
  }
}
